//
//  JDCompletedViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/6/24.
//

import UIKit
import JXSegmentedView
/// 已完成
class JDCompletedViewController: JDBaseViewController {
    
    var baseVC: UIViewController?
    var mainTableView: UITableView?
    var orderListModels: [JDOrderListModel?]?
    
    var isFirstLoad: Bool = true
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isFirstLoad == false {
            self.getNetData(true)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .commonColor()
        self.setupUIElements()
        self.getNetData()
        NotificationCenter.default.addObserver(self, selector: #selector(changeCurrentIndex(_:)), name: NSNotification.Name("changeOrderIndex"), object: nil)
        self.isFirstLoad = false 
        // Do any additional setup after loading the view.
    }
    
    @objc func changeCurrentIndex(_ notification: Notification) {
            
        let object = notification.object as? Int
        if object == 3 {
            self.currentPage = 1
            self.getNetData()
        }
    }
    
    func setupUIElements() {
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(-UIDevice().safeAreaInset.top)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(JDOrderTableViewCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.register(JDOrderListReleaseCell.self, forCellReuseIdentifier: "releaseCell")
        self.mainTableView?.backgroundColor = self.commonColor
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
    }
    
    //    1:"买家待付款"
    //    2:"未付款自动取消"
    //    3:"已付款(待接单)"
    //    4:"买家手动取消"
    //    5:"商家已接单"
    //    6:"商家已拒单"
    //    7:"商家已发货"
    //    8:"物流已到货"
    //    9:"买家确认收货"
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        params["status"] = 9
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10

        JDNetWorkRequest(.getOrderList(params)) { responseStr in
            
            printLog("已完成--订单列表:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let models = [JDOrderListModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.orderListModels = models
                    } else {
                        self.orderListModels?.append(contentsOf: models)
                    }
                    
                }
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } error: { errorCode in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDCompletedViewController {
    /// 查看物流
    @objc func checkLogistics(_ button: UIButton) {
        let currentModel = self.orderListModels?[button.tag]
        print("查看物流:\(button.tag)")
        let deliveryInfoVC = JDDeliveryInfoViewController()
        self.hidesBottomBarPushViewController(deliveryInfoVC)
    }
}

extension JDCompletedViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.orderListModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let currentModel = self.orderListModels?[indexPath.row]
        if currentModel?.orderSaleType == "3" || currentModel?.orderSaleType == "4" || currentModel?.orderSaleType == "5" {
            // 发布
            let releaseCell = tableView.dequeueReusableCell(withIdentifier: "releaseCell") as? JDOrderListReleaseCell
            releaseCell?.orderType = .completed
            releaseCell?.orderModel = currentModel
             
            return releaseCell!
        } else {
        
            let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDOrderTableViewCell
           
            // 交易完成
            cell?.cancelButton?.addTarget(self, action: #selector(checkLogistics(_:)), for: .touchUpInside)
            cell?.cancelButton?.tag = indexPath.row
           
            cell?.orderType = .completed
            cell?.orderModel = currentModel
            
            
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 100
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        printLog("已完成->点击:\(indexPath.row)")
        let currentModel = self.orderListModels?[indexPath.row]
        
        if currentModel?.orderSaleType == "3" || currentModel?.orderSaleType == "4" || currentModel?.orderSaleType == "5" {
            //  龙看板样式
            let simpleOrderVC = JDSimpleOrderDetailViewController()
            simpleOrderVC.orderType = .completed
            simpleOrderVC.orderId = currentModel?.orderId
            self.baseVC?.hidesBottomBarPushViewController(simpleOrderVC)
        } else {
            
            let newOrderDetailVC = JDNewOrderDetailViewController()
            newOrderDetailVC.shopName = currentModel?.shopName
            newOrderDetailVC.orderType = .completed
            newOrderDetailVC.orderId = currentModel?.orderId
            self.baseVC?.hidesBottomBarPushViewController(newOrderDetailVC)
            
//            let orderDetailVC = JDOrderDetailViewController()
//            orderDetailVC.shopName = currentModel?.shopName
//            orderDetailVC.orderId = currentModel?.orderId
//            orderDetailVC.orderType = .completed
//            self.baseVC?.hidesBottomBarPushViewController(orderDetailVC)
        }
    }
    
}

extension JDCompletedViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}
